package beautifyTool;

import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;

public class SetTransparencyTool {
    public static WritableImage setTransparency(Image image, double opacity) {
        // 获取PixelReader
        PixelReader pixelReader = image.getPixelReader();

        // 创建WritableImage
        WritableImage wImage = new WritableImage((int) image.getWidth(), (int) image.getHeight());
        PixelWriter pixelWriter = wImage.getPixelWriter();
        // 单线程更改透明度，得到每个坐标像素点的color，并重新设值，赋予透明度，最后将新color设给新的image对象(wImage的pixelWriter)

        for (int readY = 0; readY < image.getHeight(); readY++) {
            for (int readX = 0; readX < image.getWidth(); readX++) {
                Color color = pixelReader.getColor(readX, readY);
                // 最后一个参数是透明设置。需要设置透明不能改变原来的，只能重新创建对象赋值，
                Color c1 = new Color(color.getRed(), color.getGreen(), color.getBlue(), opacity);
                pixelWriter.setColor(readX, readY, c1.brighter());
            }
        }
        return wImage;
    }
}
